package org.jsola.hr.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.jsola.hr.dto.DepInfoAddDTO;
import org.jsola.hr.provider.IPermissionProviderService;
import org.jsola.hr.service.ICompanyNecessaryFieldService;
import org.jsola.hr.service.ICustomTemplateService;
import org.jsola.hr.service.IDepInfoService;
import org.jsola.module.IModuleService;
import org.jsola.module.ModuleContext;
import org.jsola.notice.service.INoticeInitService;
import org.jsola.permission.constant.RoleTypeEnum;
import org.jsola.permission.entity.RoleDO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.entity.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;

import static org.jsola.hr.constant.HrPermissionConstants.HR_DEFAULT_SUBJECT_ID;
import static org.jsola.hr.constant.HrPermissionConstants.HR_SUBJECT_TYPE;
import static org.jsola.user.constant.UserConstants.INIT_CONTEXT_USER_KEY;

/**
 * @author june
 */
@Service
@Slf4j
public class HrModuleServiceImpl implements IModuleService {

    @Value("${spring.application.name}")
    private String applicationName;

    @Autowired
    private IPermissionProviderService permissionProviderService;
    @Autowired
    private IDepInfoService depInfoService;

    @Autowired
    private INoticeInitService noticeInitService;

    @Autowired
    @Lazy
    private ICustomTemplateService customTemplateService;

    @Autowired
    private ICompanyNecessaryFieldService companyNecessaryFieldService;

    @Override
    public ModuleContext initSite(ModuleContext moduleContext) {
        // 用户
        UserDO userDO = moduleContext.get(INIT_CONTEXT_USER_KEY);
        TokenUser tokenUser = new TokenUser(moduleContext.getCurrUserId(),moduleContext.getSiteId());
        // 初始化一个一级组织
        initDeptInfo(moduleContext.getSiteName(),tokenUser);
        // 初始化人力系统管理员
        initHrAdminRoleMember(userDO.getId(),moduleContext.getSiteId());
        log.info("初始化人力系统完成，siteId:{}",moduleContext.getSiteId());
        // 初始化通知
        // noticeInitService.init("hr", tokenUser);
        // 初始化租户级默认入职模板
        customTemplateService.saveDefaultBySite(tokenUser);
        // 初始化租户级花名册必填字段
        companyNecessaryFieldService.necessaryInitializationByCompanyId("site", tokenUser);
        return moduleContext;
    }

    /**
     * 初始化一个一级组织
     * @param siteName 租户名称
     * @param tokenUser 用户
     */
    private void initDeptInfo(String siteName,TokenUser tokenUser) {
        DepInfoAddDTO depInfoAddDTO = new DepInfoAddDTO();
        depInfoAddDTO.setName(siteName);
        depInfoAddDTO.setParentId("0");
        depInfoAddDTO.setLevel(1);
        depInfoAddDTO.setCode(tokenUser.getSiteId());
        depInfoAddDTO.setVirural(false);
        depInfoAddDTO.setCompanyId("0");
        depInfoAddDTO.setType(0);
        depInfoAddDTO.setSort(100);
        depInfoService.save(depInfoAddDTO,tokenUser);
        log.info("初始化人力系统新建部门成功，siteId:{}",tokenUser.getSiteId());
    }

    /**
     * 初始化人力系统管理员
     * @param userId 超管
     * @param siteId 当前站点
     */
    private void initHrAdminRoleMember(String userId,String siteId){
        List<RoleDO> roleList = permissionProviderService.querySiteRoleList(HR_SUBJECT_TYPE,siteId);
        if (CollectionUtils.isEmpty(roleList)) {
            log.warn("人力系统下没有角色，siteId:{},userId:{}",siteId,userId);
            return;
        }
        TokenUser tokenUser = new TokenUser(userId,siteId);
        Optional<RoleDO> optionalRoleDO = roleList.stream().filter(roleDO -> roleDO.getType().equals(RoleTypeEnum.ADMIN.getValue())).findFirst();
        if (optionalRoleDO.isPresent()) {
            RoleDO role = optionalRoleDO.get();
            permissionProviderService.addRoleMember(userId,role.getId(),HR_SUBJECT_TYPE,HR_DEFAULT_SUBJECT_ID,tokenUser);
            log.info("初始化人力系统管理员完成，siteId:{},userId:{}",siteId,userId);
            return;
        }
        log.error("没有找到人力系统管理员角色，siteId:{},userId:{}",siteId,userId);
    }


    @Override
    public ModuleContext destroySite(ModuleContext moduleContext) {
        return moduleContext;
    }

    @Override
    public String getModuleName() {
        return applicationName;
    }
}
